package com.leyou.order.interceptor;

import com.leyou.common.auth.pojo.AppInfo;
import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.constants.LyConstants;
import com.leyou.order.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 商品服务token拦截（校验）
 */
@Component
@Slf4j
public class AppTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProps;

    /**
     * 在Controller执行之前
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        //1.从请求头中获取服务token
        String appToken = request.getHeader(LyConstants.APP_TOKEN_HEADER);

        //2.校验服务token合法性
        Payload<AppInfo> payload = null;

        try {
            payload = JwtUtils.getInfoFromToken(appToken, jwtProps.getPublicKey(), AppInfo.class);
        } catch (Exception e) {
            log.error("【商品服务token验证】验证失败，原因："+e.getMessage());
            //拒绝访问
            return false;
        }

        //3.如果合法，取出服务token的targetList（合法目标服务列表）
        AppInfo info = payload.getInfo();
        List<String> targetList = info.getTargetList();

        //4.判断当前服务名称是否在targetList（合法目标服务列表）中
        if(!targetList.contains(jwtProps.getApp().getServiceName())){
            log.error("【服务token验证】验证失败，该服务不属于合法服务");
            //拒绝访问
            return false;
        }

        //5.如果在里面，放行，否则拒绝访问
        return true;
    }
}

